#include "widget.h"
#include<QtCore/QObject>
#include "ui_widget.h"
#include <QDebug>

QString stttr;

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    pix.load(":/2.jpg");

    ui->open_btn->resize(80,80);
    ui->open_btn->setStyleSheet("border-image: url(:/2.jpg);border:none;");
    qmlRegisterType<Gemini>("an.qml.TransObj", 1, 0, "TransObj");
}


Widget::~Widget()
{
    delete ui;
}


void Widget::on_open_btn_clicked()
{
    this->hide();
    engine.load("qrc:/scan.qml");

    qob = engine.rootObjects().value(0);
    window = qobject_cast<QQuickWindow *>(qob);
    window->show();
    this->show();

}



Gemini::Gemini(QWidget *parent) :
    QWidget(parent)
{

}
Gemini::~Gemini()
{

}


void Gemini::threadExit()
{
    mythread.wait();
    mythread.quit();
}

void Gemini::connectedSlot()
{
    qDebug() << "链接";
}
void Gemini::disconnectedSlot()
{
    qDebug() << "断开连接";
}
void Gemini::recvDataSlot()
{
    //从缓冲区中读消息
    QString str;
    QByteArray arr = socket->readLine();
    str = QString::fromUtf8(arr.data(),18);
    qDebug() << "read = " << str;

    stttr = str;
    emit threadDone();
}

void Gemini::run()
{
   connect(&mythread,SIGNAL(threadDone()),this,SLOT(threadExit()));
}

void Gemini::getValFromQml(int v)
{

    mythread.start();
    //connect(this,SIGNAL(sendarr(QString str)),Widget,SLOT(displaystr(Qstring str)));
    socket = new QTcpSocket(this);
    connect(socket,SIGNAL(connected()),this,SLOT(connectedSlot()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(disconnectedSlot()));
    //当有新消息来时，连接套接字就会有信号产生，
    connect(socket,SIGNAL(readyRead()),this,SLOT(recvDataSlot()));


    socket->connectToHost("121.196.49.0",8080);

    if(v > 0)
    {
        QString str = QString::number(v,10);
        QByteArray arr;
        arr.append(str);
        int i = 0;
        i = socket->write(arr);
        if(i < 0)
        {
            qDebug() << "error";
        }
        else
        {
            qDebug() << "OK";
        }
    }
    emit valueFromCpp(v);

}

void Widget::on_recv_btn_clicked()
{
    ui->label->setText(stttr);
}
